from django.core.cache import cache
from rest_framework.views import APIView
from django.conf import settings
from utils.response import APIResponse
from utils import throttlings
from . import models
from . import serializers
from libs.sms import SMS
import re

class MobileAPIView(APIView):

    def post(self, request, *args, **kwargs):
        mobile = request.data.get('mobile')
        if not re.match(r'^1[3-9][0-9]{9}$', mobile):
            return APIResponse(status=1, msg='手机号有误', http_status=400)
        try:
            user_obj = models.User.objects.get(is_active=True, mobile=mobile)
        except:
            return APIResponse(msg='手机号未注册')
        return APIResponse(msg='手机号已注册')


class LoginAPIView(APIView):

    permission_classes = []
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        serializer = serializers.LoginModelSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        return APIResponse(results={
            'username': serializer.username,
            'token': serializer.token
        })


class SMSAPIView(APIView):

    throttle_classes = [throttlings.SmsThrottling]

    def post(self, request, *args, **kwargs):
        mobile = request.data.get('mobile')
        # 只需判断是否正确，不需要判断是否注册
        if not re.match(r'^1[3-9][0-9]{9}$', mobile):
            return APIResponse(status=1, msg='手机号有误', http_status=400)

        code = SMS.get_code()
        if SMS.send_sms(mobile, code, settings.SMS_EXP):
            cache.set(settings.SMS_KEY % mobile, code, settings.SMS_EXP * 60)
            return APIResponse(msg="信息发送成功")
        return APIResponse(status=1, msg='信息发送失败', http_status=500)


class RegisterAPIView(APIView):
    permission_classes = []
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        serializer = serializers.RegisterModelSerializer(data = request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return APIResponse(msg="用户注册成功")


class LoginMobileAPIView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        serializer = serializers.LoginMobileModelSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        return APIResponse(results={
            'username': serializer.username,
            'token': serializer.token
        })
